package com.sakura.mybatis.version3.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.sakura.mybatis.version3.mapper.DataMapper;
import com.sakura.mybatis.version3.pojo.PatientVO;
import com.sakura.mybatis.version3.pojo.ProjectVO;
import com.sakura.mybatis.version3.utils.SqlSessionUtils;
import org.apache.ibatis.session.SqlSession;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.List;
import java.util.Map;

/**
 * @Author Sakura
 * @Date 2023/6/7 13:52
 * @Version 1.0
 */
public class PatientExcelListener extends AnalysisEventListener<PatientVO> {

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 1000;

    private static int count = 0;

    /**
     * 缓存的数据
     */
    private List<PatientVO> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    @Override
    public void invoke(PatientVO patientVO, AnalysisContext analysisContext) {
        cachedDataList.add(patientVO);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    //读取表头内容
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        System.out.println("表头信息:"+ JSON.toJSONString(headMap));
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~数据读取结束~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    }

    private void saveData() {
        SqlSession sqlSession = null;
        try {
            String pathName = "config/mybatis/version3/mybatis-config.xml";
            sqlSession = SqlSessionUtils.getSqlSession(pathName, false);
            DataMapper mapper = sqlSession.getMapper(DataMapper.class);
            for (PatientVO patientVO : cachedDataList) {
                mapper.savePatientData(patientVO);
            }
            sqlSession.commit();
            sqlSession.clearCache();
            count += cachedDataList.size();
        } catch (Exception e) {
            count -= cachedDataList.size();
            sqlSession.rollback();
            System.out.println("文件写入异常!");
        } finally {
            if (null != sqlSession) {
                sqlSession.close();
            }
        }

    }
}
